#!/bin/bash

# 安卓APP打包脚本

echo "📱 开始打包安卓APP..."

# 检查是否安装了Cordova
if ! command -v cordova &> /dev/null; then
    echo "❌ Cordova未安装，正在安装..."
    npm install -g cordova
fi

# 检查是否安装了Android SDK
if [ -z "$ANDROID_HOME" ]; then
    echo "⚠️  警告: ANDROID_HOME环境变量未设置"
    echo "请安装Android Studio并设置ANDROID_HOME环境变量"
    echo "通常路径为: /home/用户名/Android/Sdk"
fi

# 创建Cordova项目（如果不存在）
if [ ! -d "mobile" ]; then
    echo "📦 创建Cordova项目..."
    cordova create mobile com.accounting.app "记账本"
    cd mobile
    cordova platform add android
    cd ..
fi

# 构建前端项目
echo "🔨 构建前端项目..."
cd frontend
npm run build
cd ..

# 复制构建文件到Cordova项目
echo "📋 复制文件到Cordova项目..."
rm -rf mobile/www/*
cp -r frontend/dist/* mobile/www/

# 更新Cordova配置
echo "⚙️  更新Cordova配置..."
cat > mobile/config.xml << 'EOF'
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.accounting.app" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>记账本</name>
    <description>一个简单易用的记账本应用</description>
    <author email="team@accounting.app" href="https://accounting.app">
        记账本团队
    </author>
    <content src="index.html" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    
    <platform name="android">
        <allow-intent href="market:*" />
        <icon density="ldpi" src="res/icon/android/ldpi.png" />
        <icon density="mdpi" src="res/icon/android/mdpi.png" />
        <icon density="hdpi" src="res/icon/android/hdpi.png" />
        <icon density="xhdpi" src="res/icon/android/xhdpi.png" />
        <icon density="xxhdpi" src="res/icon/android/xxhdpi.png" />
        <icon density="xxxhdpi" src="res/icon/android/xxxhdpi.png" />
    </platform>
    
    <preference name="DisallowOverscroll" value="true" />
    <preference name="android-minSdkVersion" value="22" />
    <preference name="android-targetSdkVersion" value="33" />
    
    <plugin name="cordova-plugin-whitelist" version="1" />
    <plugin name="cordova-plugin-network-information" version="3.0.0" />
    <plugin name="cordova-plugin-statusbar" version="4.0.0" />
    <plugin name="cordova-plugin-splashscreen" version="6.0.2" />
</widget>
EOF

# 构建安卓APP
echo "🏗️  构建安卓APP..."
cd mobile
cordova build android --release

if [ $? -eq 0 ]; then
    echo "✅ 安卓APP构建成功！"
    echo "📱 APK文件位置: mobile/platforms/android/app/build/outputs/apk/release/app-release-unsigned.apk"
    echo ""
    echo "📝 签名APK步骤："
    echo "1. 生成密钥库: keytool -genkey -v -keystore accounting-app.keystore -alias accounting -keyalg RSA -keysize 2048 -validity 10000"
    echo "2. 签名APK: jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore accounting-app.keystore app-release-unsigned.apk accounting"
    echo "3. 对齐APK: zipalign -v 4 app-release-unsigned.apk AccountingApp.apk"
else
    echo "❌ 构建失败，请检查错误信息"
    exit 1
fi